<?php

declare(strict_types=1);

namespace App\CustHub\Service;

use App\CustHub\Mapper\ChGetUserMapper;
use App\CustHub\Mapper\ChUserMapper;
use Carbon\Carbon;
use Hyperf\Di\Annotation\Inject;
use Mine\Abstracts\AbstractService;
use Mine\Exception\NormalStatusException;
use Mine\Helper\Str;

class ChGetUserService extends AbstractService
{
    #[Inject]
    protected ChUserMapper $userMapper;

    #[Inject]
    protected ChSeatService $seat;

    public $mapper;
    public function __construct(ChGetUserMapper $mapper)
    {
        $this->mapper = $mapper;
    }

    public function getUser($params)
    {
        return $this->mapper->getUser($params);
    }

    public function update(mixed $id, array $data): bool
    {
        return $this->mapper->update($id, $data);
    }

    public function addSeat(array $data): bool
    {
        // 数据验证
        if (!isset($data['uid']) ||!isset($data['type']) ||!isset($data['count']) ||!isset($data['expire_time'] )||!isset($data['seat_type'] ) ) {
            throw new NormalStatusException("数据不完整");
        }

        $uid = (int) $data['uid'];
        $accountType = (int) $data['type'];
        $seatType = (int) $data['seat_type'];
        $seatNum = (int) $data['count'];
        $expireTime = Carbon::parse($data['expire_time'])->timestamp;

        if ($uid <= 0 || $seatNum <= 0 || $accountType < 0) {
            throw new NormalStatusException("数据格式不正确");
        }

        $seatData = [];
        for ($i = 0; $i < $seatNum; $i++) {
            $seatData[] = [
                'uid' => $uid,
                'main_uid' => $uid,
                'code' => Str::getUUID(), // 使用 Laravel 的 Str::uuid() 生成 UUID
                'expire_time' => $expireTime,
                'type' => $accountType,
                'seat_type' => $seatType
            ];
        }

        // 增加用户席位数量
        $this->userMapper->inc($uid, $seatNum, $seatType);
        return $this->seat->batchSave($seatData);
    }
}